/*
	A helper class for many canvas-based operations.
*/

var img = new Image();

// gets the canvas drawing space.
function getContext() {
	var canvas = document.getElementById('canvasObject');
	if ( canvas.getContext ) {
		return canvas.getContext('2d');
	} else{
		// browser doesn't support canvas.
		return;
	}
}

// loads an image into the canvas.
function loadImage(url, initFn, params) {
	img.onload = function(){
		document.getElementById('sizeU').value = img.width;
		document.getElementById('sizeV').value = img.height;
		document.getElementById('canvasObject').width = img.width;
		document.getElementById('canvasObject').height = img.height;

		if ( document.getElementById('loadingImage') ) { document.getElementById('loadingImage').style.visibility = 'hidden'; }
		document.getElementById('canvasObject').style.visibility = 'visible';

		try {
			resizeImageContainer();
		} catch(e) { }
		drawImage();
		initFn(params);
	}
	img.src = url;
}

// draw the image.
function drawImage() {
	ctx = getContext();
	ctx.clearRect(0, 0, img.width, img.height);
	ctx.drawImage(img, 0, 0);
}

function getH() {
	return img.height;
}

function getW() {
	return img.width;
}

// From http://www.quirksmode.org/js/findpos.html
// finds the (x,y) coordinate of an object in the DOM.
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
		return {x:curleft,y:curtop};
	}
}		

// Finds the current location of the mouse, taking the canvas offset into account.
function mousePos (ev, canvasContainerID, offsetX, offsetY) {
	var x,y;
	var scrollLeft = document.getElementById(canvasContainerID).scrollLeft;
	var scrollTop = document.getElementById(canvasContainerID).scrollTop;
	x = ev.pageX- offsetX + scrollLeft;
	y = ev.pageY- offsetY + scrollTop;
	return {x:x, y:y};
}

function scrollChange (canvasContainerID) {
	var ic = document.getElementById(canvasContainerID);
	var top    = ic.scrollTop;
	var left   = ic.scrollLeft;
	var height = ic.offsetHeight;
	var width  = ic.offsetWidth;
	
	// these variables should be the coordinates of the image or
	// the scrolling window, whichever is smaller.
	if (height > img.height)
		height = img.height;
	if (width > img.width)
		width = img.width;
	
	var center = new Point2D(left + width / 2, top + height / 2);
	return center;
}
